package org.bmp.zemail.login.common.controllers;

import java.security.Principal;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.bmp.zemail.home.controllers.HomeController;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LoginController {

	public static final String ROOT_MAPPING = "/login";
	public static final String SUCCESS_MAPPING = "/login/success";
	
	public static final String FORM_VIEW = "login/login";
	
	@RequestMapping(LoginController.ROOT_MAPPING)
	public String initForm(HttpServletRequest request, ModelMap modelMap) {
		System.out.println("LoginControler.initForm");//TODO BM replace with logger
		
		HttpSession session = request.getSession();
		
		//if access exception, present the user with error message
		Object accessException = session.getAttribute(WebAttributes.ACCESS_DENIED_403);
		if (accessException != null) {
			String errorMessage = "Erro de acesso.";//TODO BM multi language
			session.removeAttribute(WebAttributes.ACCESS_DENIED_403);
			
			modelMap.addAttribute("errorMessage", errorMessage);
		}
		
		//if authentication exception, present the user with error message
		Object authException = session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
		if (authException != null) {
			String errorMessage = "Erro de login.";//TODO BM multi language
			session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
			
			modelMap.addAttribute("errorMessage", errorMessage);
		}
		
		//return form view
		return FORM_VIEW;
	}
	
	@RequestMapping(LoginController.SUCCESS_MAPPING)
	public String loginSuccess(HttpServletRequest request, ModelMap modelMap) {
		System.out.println("LoginControler.loginSuccess");//TODO BM replace with logger
		
		//get user from request
		Principal user = request.getUserPrincipal();
		if (user == null) {
			System.out.println("tentou ir a pagina de login success sem login feito");//TODO BM replace with logger
			return FORM_VIEW;
		}
		
		//return another controller
		return "redirect:" + HomeController.ROOT_MAPPING;
	}
	
}
